﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebServer
{
    public class RequestHelper
    {
        private HttpListenerRequest request;
        protected string _FileType = ".html";
        public RequestHelper(HttpListenerRequest request)
        {
            this.request = request;
        }

        public string FileType
        {
            get
            {
                return _FileType;
            }
        }

        public Stream RequestStream { get; set; }
        public void ExtracHeader()
        {
            RequestStream = request.InputStream;
        }

        public delegate void ExecutingDispatch(FileStream fs);
        public bool DispatchResources(ExecutingDispatch action)
        {
            var rawUrl = request.RawUrl;//资源默认放在执行程序的wwwroot文件下，默认文档为index.html
            string filePath = string.Format(@"{0}/wwwroot{1}", Environment.CurrentDirectory, rawUrl);//这里对应请求其他类型资源，如图片，文本等
            if (rawUrl.Length == 1)
                filePath = string.Format(@"{0}/wwwroot/index.html", Environment.CurrentDirectory);//默认访问文件

            _FileType = filePath.Substring(filePath.LastIndexOf('.'));
            Console.WriteLine(_FileType);

            try
            {
                if (File.Exists(filePath))
                {
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
                    action?.Invoke(fs);
                    return true;
                }else
                {
                    Debug.Log($"request file is not exist.path:{filePath}");
                    return false;
                }
            }
            catch (Exception e)
            {
                Debug.Error($"DispatchResources error:{e.Message}");
                return false;
            }
        }
        public void ResponseQuerys()
        {
            var querys = request.QueryString;
            foreach (string key in querys.AllKeys)
            {
                VarityQuerys(key, querys[key]);
            }
        }

        private void VarityQuerys(string key, string value)
        {
            switch (key)
            {
                case "pic": Pictures(value); break;
                case "text": Texts(value); break;
                default: Defaults(value); break;
            }
        }

        private void Pictures(string id)
        {

        }

        private void Texts(string id)
        {

        }

        private void Defaults(string id)
        {

        }

    }
}
